package com.thornbird.vehiclerecycling.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

public class JsonUtil {

    private static ObjectMapper objectMapper;

    private static XmlMapper xmlMapper;

    static {
        objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setDateFormat(new SimpleDateFormat(DateUtil.DATE_FORMAT));
        xmlMapper = new XmlMapper();
        xmlMapper.registerModule(new JaxbAnnotationModule());
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        xmlMapper.setDateFormat(new SimpleDateFormat(DateUtil.DATE_FORMAT));
    }

    public static <T> T parseObject(String jsonString, Class<T> clazz) {
        T object = null;
        if (jsonString != null && !jsonString.isEmpty()) {
            try {
                object = objectMapper.readValue(jsonString, clazz);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return object;
    }

    public static <T> String toJsonString(T object) {
        String jsonString = null;
        if (object != null) {
            try {
                jsonString = objectMapper.writeValueAsString(object);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return jsonString;
    }

    public static <T> String toXmlString(T object) {
        String xmlString = null;
        if (object != null) {
            try {
                xmlString = xmlMapper.writeValueAsString(object);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return xmlString;
    }

    public static <T> Map<String, Object> toMap(T object) {
        Map<String, Object> map = new HashMap<>();
        String jsonString = toJsonString(object);
        try {
            map = objectMapper.readValue(jsonString, new TypeReference<Map<String, Object>>(){});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static <T> T cloneObject(T object, Class<T> clazz) {
        return parseObject(toJsonString(object), clazz);
    }

}
